package com.defysoft.waukids.album;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity_UpPhoto;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.gallery.Action;
import com.defysoft.waukids.gallery.CustomGallery;
import com.defysoft.waukids.notice.Notice_Write_Photo_View;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Album_Main_Write extends BaseActivity_UpPhoto{
	boolean photo_up_check= false;
	TextView tv;
	EditText et[] = new EditText[2];
	ImageView iv_photo [] = new ImageView[10];
	ImageView iv_cancle[] = new ImageView[10];
	FrameLayout fl [] = new FrameLayout[10];
	View btn_save;
	String photo = "";
	Toolbar toolbar;
	LinearLayout ly;	
	Sqlite_Connect sqlite_Connect;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int NETWORK_ERR = 8;
	private final int PHOTO_SUCCESS = 7;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_School school;
	private ImageLoader imageLoader;
	DisplayImageOptions defaultOptions;
	ArrayList<CustomGallery> dataT ;
	String[] all_path;
	Bitmap bitmap;
	int count;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
			
    if (requestCode == 200 && resultCode == Activity.RESULT_OK) {			
			imageLoader.clearDiskCache();
			imageLoader.clearMemoryCache();
			
			all_path = data.getStringArrayExtra("all_path");	
			dataT = new ArrayList<CustomGallery>();
			
			for (String string : all_path) {
				CustomGallery item = new CustomGallery();
				item.sdcardPath = string;
				dataT.add(item);
			}
			//이미지뷰 초기화
			image_clear();
			
		for (int i = 0; i < dataT.size(); i++) {			
				 final int count = i;	
				 //사진 셋팅
				 image_setting(i);
				 //이미지 삭제 버튼
				 iv_cancle[i].setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						//이미지뷰 초기화	
						dataT.remove(count);
						image_clear();
						all_path = new String[dataT.size()];
						for (int j = 0; j < dataT.size(); j++) {
							all_path[j] = dataT.get(j).sdcardPath;
							image_setting(j);
						}						
					}
				 });				 
				}
		 	}		 
		}
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.album_main_write);
		setStartData();
		setStartToolbar();
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	
	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		
		dataT = new ArrayList<CustomGallery>();
		Init();
		sqlite_Connect = new Sqlite_Connect(this);
		psf= new PublicSharedpreferences(this);
		psf.setMembersp();
		psf.setSchoolsp();
		school = psf.getSchoolsp();
		member = psf.getMembersp();
		toolbar = (Toolbar) findViewById(R.id.ALBUM_MAIN_WRITE_TOOLBAR);
		btn_save = (View) findViewById(R.id.ALBUM_WRITE_TOOLBAR_SAVE);
		tv = (TextView) findViewById(R.id.ALBUM_MAIN_PHOTO_UP);
		et[0] = (EditText) findViewById(R.id.ALBUM_MAIN_TITLE);
		et[1] = (EditText) findViewById(R.id.ALBUM_MAIN_SUB);
		ly = (LinearLayout)findViewById(R.id.ALBUM_MAIN_PHOTO_CONTAINER);
		photo_ImageContainer();

		tv.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
				i.putExtra("path", all_path);
				startActivityForResult(i, 200);		
			}
		});
		btn_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog();
												
			}
		});
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				switch (cho) {
				case 0:
					mainThread();
					break;

				default:
					break;
				}

			}
		});
		firstThread.start();
		if(dataT.size()==0){
			startDIal();
		}
	}

		@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);

		switch (_message.what) {
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}			
			endDIal();
			Toast.makeText(this, "작성 완료 되었습니다.", Toast.LENGTH_SHORT).show();
			setResult(PublicConstant.REFRESH_CODE);
			finish();
			break;

		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			if (upThread != null) {
				upThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		case NETWORK_ERR:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			if (upThread != null) {
				upThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Album_Main_Write", member.Email);
			break;
		case PHOTO_SUCCESS:
			if (upThread != null) {
				upThread.interrupt();
			}
				startNetwork(0);
			
			break;
		}

	}

	void mainThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_ALBUM_MAIN_WRITE+ "&subject="
							+ et[1].getText().toString() + "&title="
							+ et[0].getText().toString() + "&email="
							+ member.Email + "&sch=" + member.School
							+ "&class=" + member.Class + "&photo=" + photo));

			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" where mainThread()");
		}
	}
	
	void check_Contents(){
			int check =0;
		if(et[0].getText().toString().length()<2 ){
			Toast.makeText(this, "제목을 2글자 이상으로 입력해주세요", Toast.LENGTH_SHORT).show();
			check=1;
		}
		if(et[1].getText().toString().length()<2){
			Toast.makeText(this, "내용을 2글자 이상으로 입력해주세요.", Toast.LENGTH_SHORT).show();
			check=1;
		}
		if(check==0){
			
			if(dataT.size()==0 ){
				Toast.makeText(this, "사진첩은 사진을 1장 이상 등록하셔야 됩니다.", Toast.LENGTH_SHORT).show();
			}else{
				image_bitmap();	
			}
					
		}
	}
	
	//이미지 로더 옵션
	void Init(){
				defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
				.considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024)
				.memoryCacheSizePercentage(20)
				.diskCacheSize(50 * 1024 * 1024)
				.diskCacheFileCount(100)
				 .diskCacheExtraOptions(480, 320, null) 
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(config);
	}
	
	void photo_ImageContainer(){
		iv_photo[0] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_1);
		iv_photo[1] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_2);
		iv_photo[2] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_3);
		iv_photo[3] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_4);
		iv_photo[4] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_5);
		iv_photo[5] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_6);
		iv_photo[6] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_7);
		iv_photo[7] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_8);
		iv_photo[8] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_9);
		iv_photo[9] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_10);
		
		iv_cancle[0] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_1);
		iv_cancle[1] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_2);
		iv_cancle[2] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_3);
		iv_cancle[3] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_4);
		iv_cancle[4] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_5);
		iv_cancle[5] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_6);
		iv_cancle[6] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_7);
		iv_cancle[7] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_8);
		iv_cancle[8] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_9);
		iv_cancle[9] = (ImageView) findViewById(R.id.ALBUM_MAIN_PHOTO_CANCLE_10);
		
		fl [0] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_1);
		fl [1] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_2);
		fl [2] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_3);
		fl [3] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_4);
		fl [4] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_5);
		fl [5] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_6);
		fl [6] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_7);
		fl [7] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_8);
		fl [8] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_9);
		fl [9] = (FrameLayout) findViewById(R.id.ALBUM_MAIN_PHOTO_FRAME_10);	
	}
	
	//이미지뷰 초기화
	void image_clear(){
		if(dataT.size()==0){
			ly.setVisibility(View.GONE);
			tv.setVisibility(View.VISIBLE);
		}else{
			tv.setVisibility(View.GONE);
			ly.setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < 10; i++) {
			fl[i].setVisibility(View.GONE);
			iv_cancle[i].setVisibility(View.GONE);
			iv_photo[i].setVisibility(View.GONE);
			iv_photo[i].setImageResource(0xff3366FF);
		}
	}
	
	//이미지뷰 셋팅
	void image_setting(int i){
		final int count = i;	
		 fl[i].setVisibility(View.VISIBLE);
		 iv_photo[i].setScaleType(ScaleType.FIT_XY);				
		 iv_photo[i].setVisibility(View.VISIBLE);
		 iv_cancle[i].setVisibility(View.VISIBLE);
		 	if(i==9){
			 
		 	}else{
		 		fl[i+1].setVisibility(View.VISIBLE);
		 		iv_photo[i+1].setVisibility(View.VISIBLE);
		 		iv_cancle[i+1].setVisibility(View.GONE);
		 		iv_photo[i+1].setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
						i.putExtra("path", all_path);
						startActivityForResult(i, 200);			
					}
				});
		 	}			 	
		 	
		 imageLoader.displayImage("file://" + dataT.get(i).sdcardPath,iv_photo[i],defaultOptions);
		//이미지 클릭시  
		 iv_photo[i].setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Album_Main_Write.this,Notice_Write_Photo_View.class);
				intent.putExtra("path", all_path);
				intent.putExtra("count", count+"");
				startActivity(intent);
			}
		});	
	}
	
	@Override
	public void upImageThread(int choice) {
		super.upImageThread(choice);
		final int cho = choice;
	 upThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 0; i < dataT.size(); i++) {
				JSONObject jsonObject = null;
				try {
					
						StringBuffer postDataBuilder = new StringBuffer();
						// 추가하고 싶은 Key & Value 추가key & value를 추가한 후 꼭 경계선을 삽입해줘야
						// 데이터를 구분할 수 있다.파일 첨부
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("filename", "album"));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("folder", "albumphoto"));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setFile("photo", "temp.jpg"));
						postDataBuilder.append("\r\n");
						// 커넥션 생성 및 설정
						HttpURLConnection conn = (HttpURLConnection) new URL(
								HTTP_URL_PHOTOUP)
								.openConnection();
						conn.setDoInput(true);
						conn.setDoOutput(true);
						conn.setUseCaches(false);
						conn.setRequestMethod("POST");
						conn.setRequestProperty("Connection", "Keep-Alive");
						conn.setRequestProperty("Content-Type",
								"multipart/form-data;boundary=" + boundary);// 전송
																			// 작업
																			// 시작
						DataOutputStream out = new DataOutputStream(new BufferedOutputStream(conn.getOutputStream()));
						// 위에서 작성한 메타데이터를 먼저 전송한다. (한글이 포함되어 있으므로 UTF-8 메소드사용)
						out.writeUTF(postDataBuilder.toString());
					
					
						//사진 리사이징 && 사진 방향 지정 코드
						byte[] buffer = resizeBitmap(Album_Main_Write.this, dataT.get(i).sdcardPath);	
					    
						
						// 버퍼 크기만큼 파일로부터 바이트 데이터를 읽는다.전송
						out.write(buffer);
						out.writeBytes(delimiter); // 반드시 작성해야 한다.
						out.flush();
						out.close();
						
						// 전송끝, 피드백
						BufferedReader br = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));
						String checkmsg;
						String msg = br.readLine();
						while ((checkmsg = br.readLine()) != null) {
							msg += checkmsg;
						}
						jsonObject = new JSONObject(msg);
						if (jsonObject.getString("success").equals("true")) {
							//성공처리
							if(photo.equals("")){
								photo = jsonObject.getString("payload");
								}else{
								photo +="|"+jsonObject.getString("payload");
								}
							photo_up_check = true;
						} else {
							onNetworkCallback(FAIL, jsonObject.getString("message"));
							photo_up_check = false;
						}
				} catch (Exception e) {
					onNetworkCallback(NETWORK_ERR, e.toString()+" where upImageThread()");
					photo_up_check = false;
					}
				}
		if(photo_up_check==true){
				onNetworkCallback(PHOTO_SUCCESS,"");
		}
			}		
				
		});
		upThread.start();
		if(count==0){
			startDIal();
		}	
	}
	
	void image_bitmap(){
		upImageThread(0);
	}
	
	// 네.아니오.선택다이얼로그
			void alertDialog() {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(
						this);
				AlertDialog alert;
				builder.setMessage("사진첩을 등록 하시겠습니까?")
						.setCancelable(false)
						.setPositiveButton("네", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								check_Contents();	
							}
						})
						.setNegativeButton("아니오",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				alert = builder.create();
				alert.show();
			}
			
			private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
				public void onReceive(Context context, Intent intent) {
					LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
					TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
					Toast toast = new Toast(Album_Main_Write.this);
					toast.setView(layout);
					toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
					toast.setDuration(Toast.LENGTH_LONG);
					toast.show();
				}
			};

			
}
